package at.codebase.web.servlets.api;

import java.util.ArrayList;

import org.json.simple.JSONObject;

import at.codebase.db.dao.EItemDao;
import at.codebase.db.entities.EImage;
import at.codebase.db.entities.EItem;
import at.codebase.db.entities.EUser;
import at.codebase.web.util.LocalRequest.RequestInformation;
import at.codebase.web.util.URLParameters.ParameterException;
import at.codebase.web.util.servlet.ApiSecureServlet;

import com.googlecode.objectify.Key;

public class ItemAPIServlet extends ApiSecureServlet {

	@SuppressWarnings("unchecked")
	@Override
	protected JSONObject processRequest(RequestInformation requestInfo, String authToken) {
		try {
			long itemId = requestInfo.getParameters().getLong("item_id");
			JSONObject result = successResult();
			
			EItem item = EItemDao.getItemById(new Long(itemId));
			if(item != null && item.isActive() && !item.isExpired()){
				result.put("itemId", new Long(itemId));
				result.put("test", "testdata");
				
				result.put("title", item.getTitle());
				result.put("description", item.getDescription());
				
				
					JSONObject sellerObj = new JSONObject();
					EUser userSeller = item.getSeller().get();
					sellerObj.put("id", userSeller.getId());
					sellerObj.put("username", userSeller.getUsername());
				result.put("seller", sellerObj);
				
				ArrayList<Key<EImage>> images = item.getImageKeys();
				if (images.size() > 0) {
					result.put("image", requestInfo.getHostUrl()+"/service/image?id=" + images.get(0).getId() + "&w=110&h=110");
				} else {
					result.put("image", "");
				}
				
				result.put("price", item.getPrice()+" USD");
				result.put("url", requestInfo.getHostUrl()+"/item/"+item.getId());
				
				if(item.getLocation() != null){
					JSONObject locationObj = new JSONObject();
					locationObj.put("latitude", new Double(item.getLatitude()));
					locationObj.put("longitude", new Double(item.getLongitude()));
					result.put("location", locationObj);
				}
				
				return result;	
			}
			
			return badRequestResult("Item with id="+itemId+" not found");
			
		} catch (ParameterException e) {
			return badRequestResult("Parameters invalid");
		}
		
	}

}
